﻿/// <reference path="../../Scripts/jquery-1.7.2-vsdoc.js" />
/// <reference path="ProggyCore.js" />

Proggy.ContentEdit = function () {

    // marker
    var beforeSaveMethodsRun = false;
    var saving = false;

    // bind tabbing
    this.BindTabs = function () {

        // variables
        var /*mainArea,*/ /*theTabs,*/tabsMoved, tabsInners, tabsInnerMoved, h3s

        // set vairables
        //mainArea = jQuery("#tabs");
        tabsMoved = jQuery("#tabs-moved");
        tabsInnerMoved = jQuery("#tabs-inner-moved");
        //theTabs = jQuery(".tab");
        tabsInners = jQuery(".tab-inner");
        //h3s = theTabs.find("h3");
        h3s = tabsMoved.find("h3");

        // move
        //tabsMoved.prepend(h3s);
        //tabsInnerMoved.append(tabsInners);

        // hide
        tabsInners.hide();

        // show 
        tabsMoved.show();
        tabsInnerMoved.show();

        // bind h3 clicks
        h3s.click(function () {

            // get this
            var tab = jQuery(this);

            // get name
            var name = tab.data("tab");

            // get matching inner
            var inner = jQuery("div.tab-inner[data-tab='" + name + "']");

            // hide inners
            tabsInners.hide();

            // add class to all
            h3s.attr("class", "tab-closed");
            tab.attr("class", "tab-open");

            // show this
            inner.show();

        });

        // open first
        jQuery(h3s[0]).click();

    };

    // check for validation
    this.CheckForValidationErrors = function () {

        // find
        var errors = jQuery(".input-validation-error");
        var validationSummary = jQuery(".validation-summary-errors > ul > li");

        // hide success
        if (errors.size() > 0 || validationSummary.size() > 0) {

            //
            jQuery("div#success").remove();

            // convert model errors
            this.ConvertErrorsToSuccessDiv();
        }
    };

    // Converts model errors to friendly messag
    this.ConvertErrorsToSuccessDiv = function () {

        // tab to open
        var tabToOpen;
        var tabToOpenName;

        // create div
        jQuery("#content")
                .prepend(
                "<div id=\"success\" class=\"page_text_close_32\" style=\"display: none;\">" +
                "<div class=\"successText\">" +
                "</div></div>");

        // get success text
        var successText = jQuery("div#success > .successText:eq(0)");

        // get summary
        var summary = jQuery("div.validation-summary-errors:eq(0)");

        // get last
        var last = summary.find("li").last();

        // check
        if (last.html() == window.CHANGES_NOT_SAVED) {
            last.addClass("proggy-changes-not-saved");
        }

        // move
        successText.append(summary);

        // get msgs
        var lis = summary.find("li");

        // try to find first input validation error (ie core stuff)
        var inputVlErr = jQuery(".input-validation-error:eq(0)");

        // check
        if (inputVlErr.size == 1) {

            // use this to find tab
            var tabInner = inputVlErr.parentsUntil("#tabs-inner-moved", ".tab-inner");

            // get name
            tabToOpenName = tabInner.data("tab");
        }
        else {

            // get span
            var span = jQuery("span.proggy-custom-data-message:eq(0)");

            // get name
            tabToOpenName = span.data("tab");
        }

        // find tab
        var tab = jQuery("h3[data-tab='" + tabToOpenName + "']:eq(0)");

        // click
        tab.click();

        // show summary
        new Proggy.Static.CheckForSuccess();
    };

    // iterates before saves
    this.IterateBeforeSaveMethods = function (optionalCallback) {

        // check
        if (!beforeSaveMethodsRun) {

            // iterate methods
            jQuery.each(Proggy.ContentEdit.Static.BeforeSaveMethods, function (index_, method_) {

                method_();

            });

            // set marker
            beforeSaveMethodsRun = true;

            // callback
            if (typeof (optionalCallback) == "function") {
                optionalCallback();
            };
        }
    };

    // stop save button triggering onbeforeunload
    this.BindSaveButton = function () {

        // find buttons
        var form = jQuery("div.proggy-edit-div > form:eq(0)");

        // get func
        var theFunc = this.IterateBeforeSaveMethods;

        // bind
        form.submit(function () {

            // marker
            saving = true;

            //
            if (true) {

                // show load
                Proggy.Static.ShowLoader(function (lb, lbInner) {

                    // unbind
                    //jQuery(window).unbind("beforeunload");

                    // unbind submit
                    form.unbind("submit");

                    // iterate methods
                    theFunc();

                    //
                    window.setTimeout(function () {

                        //
                        form.trigger("submit");


                    }, 1000);

                });

            };

            return false;

        });
    };

    // bind url slug
    this.BindUrlSlug = function () {

        // get inputs
        var urlPortionInput = jQuery("input#UrlPortion");
        var contentNameInput = jQuery("input#Name");

        // check
        if (urlPortionInput.size() == 0) {

            // content edit, not initial create
            urlPortionInput = jQuery("input#UrlSlug");
        }

        // check
        if (urlPortionInput.attr("type") == "text") {

            // check
            if (urlPortionInput.size() == 0) {
                urlPortionInput = jQuery("input#UrlSlug");
            }

            //console.log(contentNameInput.attr("type"));

            // check not hidden
            if (contentNameInput.attr("type") != "hidden") {

                // put select after input
                contentNameInput.after(" &nbsp;<input checked id=\"proggy_after_name_chk\" type=\"checkbox\" /> &nbsp;Copy to url?");

                // get lock
                var copyChk = jQuery("input#proggy_after_name_chk");

                // copy function
                var copyUrlAcross = function () {

                    // get copy bool
                    var copy = copyChk.attr("checked") == "checked";

                    //
                    if (copy) {

                        // get current text
                        var currentText = contentNameInput.val();

                        // get input text allowed
                        var allowedText =
                    currentText
                        .replace(/[^a-zA-Z0-9 ]/g, "")
                        .replace(/[ ]/g, "-")
                        .toLowerCase();

                        // add
                        urlPortionInput.val(allowedText);
                    };

                };

                // bind content name input
                contentNameInput.keyup(function () {

                    copyUrlAcross();

                });

                // bind blur
                contentNameInput.blur(function () {

                    copyUrlAcross();

                });

            };
        };
    };

    // bind url slug
    this.BindUppercaseAliasInput = function () {

        // get inputs
        var uniqueAliasInput = jQuery("input#UniqueAlias");

        // check
        if (uniqueAliasInput.attr("type") == "text") {

            // bind content name input
            uniqueAliasInput.keyup(function () {

                uniqueAliasInput.val(uniqueAliasInput.val().toUpperCase().replace(/[^a-zA-Z0-9]/g, "_"));

            });

            // bind blur
            uniqueAliasInput.blur(function () {

                uniqueAliasInput.val(uniqueAliasInput.val().toUpperCase().replace(/[^a-zA-Z0-9]/g, "_"));

            });


        };
    };

    // bind publish button
    this.BindPublish = function () {

        window.setTimeout(function () {

            // set null
            window.onbeforeunload = null;

            // on before unload
            var setOnBeforeUnload = function () {

                // bind
                window.onbeforeunload = function () {

                    // check
                    if (!saving) {

                        console.log("NOT SAVING, UNLOADING");
                        return "ALL UNSAVED CHANGES WILL BE LOST";
                    }
                };
            };

            setOnBeforeUnload();

            // find button
            var button = jQuery("a.proggy-content-publish");

            // bind
            button.click(function (e) {

                //
                e.preventDefault();

                //
                window.onbeforeunload = null;

                // 
                if (confirm("Are you sure you've saved all your changes??")) {
                    window.location = button.attr("href");
                    return;
                }

                //
                setOnBeforeUnload();
            });
        }, 500);
    };

    // Init function
    this.Init = function () {

        // set unload - now set in bindPublish"
        //this.SetOnBeforeUnload();

        // bind save
        this.BindSaveButton();

        //
        this.BindTabs();

        // check for validation
        this.CheckForValidationErrors();

        //
        this.BindUrlSlug();

        //
        this.BindUppercaseAliasInput();

        //
        this.BindPublish();

        // 
        Proggy.Static.BindPreview();

        //console.log(window.onbeforeunload);
        //console.log(saving);
    };
};

// static
Proggy.ContentEdit.Static = {

    AddToBeforeSaveMethods: function (method) {

        // add
        this.BeforeSaveMethods.push(method);

    },

    BeforeSaveMethods: []

};